﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Leadtools;
using Leadtools.Codecs;
using Leadtools.WinForms;
using MINERP.BLL.InnerReturn;
using MINERP.InerReturn.Presenter;
using MINERP.MODEL.FoundationModel;
using MINERP.ComControls;
using MINERP.COM;

namespace MINERP.InerReturn.Forms
{
    public partial class FrmMain : FrmParent, IView.IFrmMain
    {
        public FrmMain()
        {
            InitializeComponent();
        }

        private MainPresenter _Presenter;
        private void FrmMain_Load(object sender, EventArgs e)
        {
            _Presenter=new MainPresenter(this);
            _Presenter.init();
            this.CurrPhoto = new List<PhotoView>();
            OriginateUserID = base.userId;
        }
        private void textEditPhotoId_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue ==13)
            {
                int length = textEditPhotoId.Text.Trim().Length;
                if(length<10)
                {
                    string NUM0 = string.Empty;
                    for (int i = 0; i < 10-length-1; i++)
                    {
                        NUM0 += "0";
                    }
                    textEditPhotoId.Text = "3" + NUM0 + textEditPhotoId.Text;
                }
                this.CurrBarCode = textEditPhotoId.Text.Trim();
                _Presenter.GetPhotoView();
                textEditPhotoId.Text = "";
            }
        }

        public int CurrPhotoId
        {
            get; set;
        }

        public int CurrProductId
        {
            get;
            set;
        }

        public string CurrBarCode
        {
            get;
            set;
        }

        public List<PhotoView> CurrPhoto
        {
            get;
            set;
        }

        public Tb_Tech_Info CurrTech
        {
            get;
            set;
        }

        public int CurrErrUserId
        {
            get; set;
        }

        public int CurrUserId
        {
            get { return base.userId; } 
            set { } 
        }

        public int CurrTrchId
        {
            get;
            set;
        }

        public int OriginateUserID
        {
            get;
            set;
        }

        public void BanDingPhotos(List<PhotoView> views)
        {
            gridControlphotos.DataSource = views;
            gridControlphotos.RefreshDataSource();
        }

        public void BangDingUsers(List<User_Info> infos)
        {
            comboBoxUer.DisplayMember = "UserName";
            comboBoxUer.ValueMember = "UserID";
            comboBoxUer.DataSource = infos;
        }

        public void BangDingTech(List<Tb_Tech_Info> infos, string CurrTech)
        {
            //comboBoxErrFlow.DisplayMember = "TechName";
            //comboBoxErrFlow.ValueMember = "TechId";
            //comboBoxErrFlow.DataSource = infos;
            textEditCurrTech.Text = CurrTech;
            if (infos == null)
            {
                return;
            }
            int intTear = infos.Count;
            //if (intTear<=2)
            //{
            //    simpleButtonOK.Enabled = false;
            //}
            //else
            //{
            //    simpleButtonOK.Enabled = true;
            //}
            if (flowLayoutPanelFlow.Controls.Count == 0)
            {
                for (int i = 0; i < intTear; i++)
                {
                    System.Windows.Forms.Label leable = new Label();
                    System.Windows.Forms.CheckBox checkBox = new CheckBox();
                    checkBox.Text = infos[i].TechName;
                    checkBox.Tag = infos[i];
                    checkBox.AutoSize = true;
                    checkBox.Checked = true;
                    //checkBox.Enabled = false;
                    leable.Text = "->";
                    checkBox.Anchor = AnchorStyles.Left;
                    flowLayoutPanelFlow.Controls.Add(checkBox);
                    leable.Anchor = AnchorStyles.Left;
                    if (infos[i].TechName.Equals("打印管理") || infos[i].TechName.Equals("输出管理"))
                    {
                        checkBox.Enabled = false;
                    }
                    if (infos[i].TechName.Equals("调色"))
                    {
                        checkBox.Checked = false;
                    }
                    leable.AutoSize = true;
                    if (i < intTear - 1)
                    {
                        flowLayoutPanelFlow.Controls.Add(leable);
                    }
                }
            }
        }

        public void DisplayAllTech(List<Tb_Tech_Info> infos)
        {
            comboBoxErrFlow.DisplayMember = "TechName";
            comboBoxErrFlow.ValueMember = "TechId";
            comboBoxErrFlow.DataSource = infos;
        }

        //private void comboBoxErrFlow_DropDownClosed(object sender, EventArgs e)
        //{
        //    flowLayoutPanelFlow.Controls.Clear();

        //    int intEndTechId = Convert.ToInt32(((Tb_Tech_Info)comboBoxErrFlow.SelectedItem).TechId);
        //    List <Tb_Tech_Info> infos=_Presenter.GetReturnTech(intEndTechId);
        //    if (infos==null)
        //    {
        //        return;
        //    }
        //    int intTear = infos.Count;
        //    for (int i=0;i<intTear;i++)
        //    {
        //     System.Windows.Forms.Label leable = new Label();
        //        System.Windows.Forms.CheckBox checkBox = new CheckBox();
        //        checkBox.Text = infos[i].TechName;
        //        checkBox.Tag = infos[i];
        //        checkBox.AutoSize = true;
        //        checkBox.Checked = true;
        //        leable.Text = "->";
        //        checkBox.Anchor = AnchorStyles.Left;
        //        flowLayoutPanelFlow.Controls.Add(checkBox);
        //        leable.Anchor = AnchorStyles.Left;
        //        leable.AutoSize = true;
        //        if (i < intTear - 1)
        //        {
        //            flowLayoutPanelFlow.Controls.Add(leable);
        //        }
        //    }

        //}

        private void simpleButtonOK_Click(object sender, EventArgs e)
        {
            Tb_Tech_Info techInfo = (Tb_Tech_Info) comboBoxErrFlow.SelectedItem;
            var arrCon = flowLayoutPanelFlow.Controls;
            List<Tb_Tech_Info> techInfos = new List<Tb_Tech_Info>();
            foreach (Control con in arrCon)
            {
                if(con.Tag!=null&&con.Tag.GetType().Name.Equals("Tb_Tech_Info"))
                {
                    CheckBox CB = ((CheckBox) (con));
                    if (CB.Checked == true)
                    {
                        techInfos.Add((Tb_Tech_Info)CB.Tag);
                    }
                }
            }
            if (techInfos.Count<1)
            {
                if (this.CurrPhoto.Count<1)
                {
                    MessageBox.Show("未选择照片。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                else
                {
                    MessageBox.Show("加载返工流程为空,产品处于 调色状态 不能返工。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
            if (CurrErrUserId == 0)
            {
                MessageBox.Show("请选择责任流程！！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            _Presenter.CreateReturnOrder(techInfos, richTextBoxRemark.Text.Trim(), techInfo.TechId);
            MessageBox.Show("返工单创建成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.CurrPhoto.Clear();
            this.CurrProductId = 0;
            CurrErrUserId = 0;
            CurrBarCode = "";
            this.flowLayoutPanelFlow.Controls.Clear();
            BanDingPhotos(CurrPhoto);
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void simpleButtonCancel_Click(object sender, EventArgs e)
        {
            this.CurrPhoto.Clear();
            this.CurrProductId = 0;
            CurrBarCode = "";
            this.flowLayoutPanelFlow.Controls.Clear();
            BanDingPhotos(CurrPhoto);
            textEditCurrTech.Text = "";
        }

      

        private void comboBoxErrFlow_SelectionChangeCommitted(object sender, EventArgs e)
        {
            comboBoxErrUser.Enabled = true;
            int techId=((Tb_Tech_Info) comboBoxErrFlow.SelectedItem).TechId;
            User_Info info= _Presenter.GetUser(techId);
            if (info == null)
            {

                //MessageBox.Show("流程未到您选择节点", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //textEditUser.Text = "";
                //this.CurrErrUserId = 0;

                List<User_Info> infos = _Presenter.GetUsersByTechId(techId);
                if (infos != null)
                {
                    comboBoxErrUser.DisplayMember = "UserName";
                    comboBoxErrUser.ValueMember = "UserID";
                    comboBoxErrUser.DataSource = infos;
                }
                else
                {
                     BLL.InnerReturn.InnerReturnBLL _bll = new InnerReturnBLL();
                     comboBoxErrUser.DisplayMember = "UserName";
                     comboBoxErrUser.ValueMember = "UserID";
                     comboBoxErrUser.DataSource = _bll.GetAllTech(); ;
                    
                }

                return;
            }
            else if(info.UserID==0)
            {
                MessageBox.Show("请先填写返单照片！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                
            }
            else
            {
                comboBoxErrUser.Enabled = false;
                comboBoxErrUser.Text = info.UserName;
                this.CurrErrUserId = info.UserID;
            }
        }

        private void simpleButtonchakan_Click(object sender, EventArgs e)
        {

            List<string> displayString =new List<string>();
            foreach (PhotoView c in CurrPhoto)
            {
               
                displayString.Add(c.picPath);
                displayString.Add(c.PhotoBarCode);

            }
            if(displayString.Count==0)
            {
                MessageBox.Show("请先填写返单照片！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            else
            {
                try
                {
                    BigPicViewer viewer = new BigPicViewer();
                    viewer.PhotoPaths = displayString;
                    viewer.CurrentIndex = 0;
                    viewer.ShowDialog();
                }catch(Exception ex)
                {
                    MessageBox.Show("读取照片失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
            }
        }

        private void comboBoxErrUser_SelectionChangeCommitted(object sender, EventArgs e)
        {
            this.CurrErrUserId=((User_Info) comboBoxErrUser.SelectedItem).UserID;
        }

        private void comboBoxUer_SelectionChangeCommitted(object sender, EventArgs e)
        {
            this.OriginateUserID = ((User_Info)comboBoxUer.SelectedItem).UserID;
        }

        private void simpleButtonChangeDisplay_Click(object sender, EventArgs e)
        {
            if(splitContainerListOrImage.Panel1Collapsed==false)
            {
                splitContainerListOrImage.Panel1Collapsed = true;
                splitContainerListOrImage.Panel2Collapsed = false;
                ///显示缩略图
                rasterThumbnailBrowserPicView.Items.Clear();
                foreach (PhotoView photo in this.CurrPhoto)
                {
                    try
                    {
                        RasterCodecs.Startup();
                        RasterCodecs codecs = new RasterCodecs();
                        CodecsThumbnailOptions options = new CodecsThumbnailOptions();
                        options.Resample = true;
                        options.LoadStamp = true;
                        options.MaintainAspectRatio = true;
                        RasterImage img;
                        try
                        {
                            img = codecs.ReadThumbnail(photo.picPath, options, 1);
                        }
                        catch
                        {
                            //为图片设置Stamp
                            RasterImage imgInfo = codecs.Load(photo.picPath);
                            Rectangle rc = RasterImage.CalculatePaintModeRectangle(imgInfo.Width, imgInfo.Height, new Rectangle(0, 0, 128, 128), RasterPaintSizeMode.FitAlways, RasterPaintAlignMode.Near, RasterPaintAlignMode.Near);
                            codecs.Options.Jpeg.Save.StampWidth = rc.Width;
                            codecs.Options.Jpeg.Save.StampHeight = rc.Height;
                            codecs.Options.Jpeg.Save.SaveWithStamp = true;
                            codecs.Options.Jpeg.Save.StampBitsPerPixel = 24;
                            codecs.Save(imgInfo, photo.picPath, RasterImageFormat.Jpeg, 0);
                            //重新读缩略图
                            img = codecs.ReadThumbnail(photo.PhotoBarCode, options, 1);
                        }
                        //int index = photoPath.LastIndexOf("\\");
                        //string fileName = photoPath.Substring(index + 1);
                        RasterImageListItem item = new RasterImageListItem(img, 1, photo.PhotoBarCode);
                        item.Tag = photo.PhotoBarCode;
                        rasterThumbnailBrowserPicView.Items.Add(item);
                        
                    }
                    catch { return; }
                }
            }
            else
            {
                splitContainerListOrImage.Panel1Collapsed = false;
                splitContainerListOrImage.Panel2Collapsed = true;
            }
        }

        private void tabControlMain_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControlMain.SelectedIndex == 1)
            {
                gridControlProduct.DataSource = _Presenter.GetUnComplteFanDan();
            }
        }
        int ChildProductID = 0;
        private void gridViewProduct_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                int productId =
                                   Convert.ToInt32(((DataRowView)(gridViewProduct.GetRow(e.RowHandle)))["OrderProductId"]);
                gridControlPhoto.DataSource = _Presenter.GetPhotosByProductID(productId);
                ChildProductID = productId;

            }
        }

        private void gridViewPhoto_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            if (e.Column.FieldName == "status")
            {
                int status =

                     Convert.ToInt32(((DataRowView)(gridViewPhoto.GetRow(e.RowHandle)))["status"]);
                switch (status)
                {
                    case (int)PhotoStatus.NoDistributePrinter:
                        {

                            e.DisplayText = "未分配打印机";
                        }
                        break;
                    case (int)PhotoStatus.DistributedPrinter:
                        {

                            e.DisplayText = "等待打印";
                        }
                        break;
                    case (int)PhotoStatus.PingBan:
                        {

                            e.DisplayText = "已拼版,未打印";
                        }
                        break;
                    case (int)PhotoStatus.Printed:
                        {
                            e.DisplayText = "等待分片";
                        }
                        break;
                    case (int)PhotoStatus.FenPian:
                        {
                            e.DisplayText = "分片完成";
                        }
                        break;
                    case (int)PhotoStatus.PhotoInnerReturn:
                        {
                            e.DisplayText = "照片返单中";
                        }
                        break;
                    case (int)PhotoStatus.PingBanInd:
                        {
                            e.DisplayText = "拼版中";
                        }
                        break;
                    case (int)PhotoStatus.WaitPhotoMove:
                        {
                            e.DisplayText = "照片等待移动";
                        }
                        break;
                    case (int)PhotoStatus.PhotoNotExist:
                        {
                            e.DisplayText = "照片不存在";
                        }
                        break;

                    default:
                        break;
                }
            }
        }

        private void buttonActionMain_Click(object sender, EventArgs e)
        {
            if (this.textBoxProductId.Text.Trim()!= "")
            {
               // _Presenter.ActionMainProduct(ChildProductID);
                int productid = Convert.ToInt32(this.textBoxProductId.Text);
                int intRtn = 0;
                if (MessageBox.Show("确定激活该产品？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    this.Cursor = Cursors.WaitCursor;
                    try
                    {
                        intRtn = _Presenter.ActionMainProduct(productid);
                        gridControlProduct.DataSource = _Presenter.GetUnComplteFanDan();
                        textBoxProductId.SelectAll();
                        textBoxProductId.Focus();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    finally
                    {
                        this.Cursor = Cursors.Default;
                    }
                    if (intRtn == -1)
                    {
                        MessageBox.Show("产品不存在！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("激活成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }

            }
            else
            {
                MessageBox.Show("请选择内部返单！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
 
            }
        }

        //private void gridViewPhotos_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        //{
        //    if(e.RowHandle>=0)
        //    {

        //    }
        //}

        
        
    }
}
